import { ref, reactive } from 'vue'

// 全局加载状态管理
interface LoadingState {
  visible: boolean
  tip: string
  description?: string
  progress?: number
  progressStatus?: 'normal' | 'exception' | 'active' | 'success'
}

const globalLoadingState = reactive<LoadingState>({
  visible: false,
  tip: '加载中...',
  description: undefined,
  progress: undefined,
  progressStatus: 'active',
})

// 加载计数器，支持多个并发加载
const loadingCounter = ref(0)

export function useGlobalLoading() {
  const showLoading = (options?: Partial<LoadingState>) => {
    loadingCounter.value++
    Object.assign(globalLoadingState, {
      visible: true,
      tip: '加载中...',
      description: undefined,
      progress: undefined,
      progressStatus: 'active',
      ...options,
    })
  }

  const hideLoading = () => {
    loadingCounter.value = Math.max(0, loadingCounter.value - 1)
    if (loadingCounter.value === 0) {
      globalLoadingState.visible = false
    }
  }

  const updateLoading = (options: Partial<LoadingState>) => {
    Object.assign(globalLoadingState, options)
  }

  const setProgress = (progress: number, status?: LoadingState['progressStatus']) => {
    globalLoadingState.progress = progress
    if (status) {
      globalLoadingState.progressStatus = status
    }
  }

  return {
    loadingState: globalLoadingState,
    showLoading,
    hideLoading,
    updateLoading,
    setProgress,
  }
}

// 局部加载状态管理
export function useLoading(initialState = false) {
  const loading = ref(initialState)
  const error = ref<Error | null>(null)

  const setLoading = (state: boolean) => {
    loading.value = state
    if (state) {
      error.value = null
    }
  }

  const withLoading = async <T>(fn: () => Promise<T>): Promise<T> => {
    try {
      setLoading(true)
      const result = await fn()
      return result
    } catch (err) {
      error.value = err instanceof Error ? err : new Error(String(err))
      throw err
    } finally {
      setLoading(false)
    }
  }

  return {
    loading,
    error,
    setLoading,
    withLoading,
  }
}

// 骨架屏加载管理
export function useSkeletonLoading() {
  const skeletonLoading = ref(true)
  const skeletonPreset = ref<'list' | 'card' | 'table' | 'form' | 'statistic' | 'chart'>('list')

  const showSkeleton = (preset?: typeof skeletonPreset.value) => {
    skeletonLoading.value = true
    if (preset) {
      skeletonPreset.value = preset
    }
  }

  const hideSkeleton = () => {
    skeletonLoading.value = false
  }

  const withSkeleton = async <T>(
    fn: () => Promise<T>,
    preset?: typeof skeletonPreset.value,
    minDuration = 500
  ): Promise<T> => {
    showSkeleton(preset)
    const startTime = Date.now()
    
    try {
      const result = await fn()
      
      // 确保最小显示时间
      const elapsed = Date.now() - startTime
      if (elapsed < minDuration) {
        await new Promise(resolve => setTimeout(resolve, minDuration - elapsed))
      }
      
      return result
    } finally {
      hideSkeleton()
    }
  }

  return {
    skeletonLoading,
    skeletonPreset,
    showSkeleton,
    hideSkeleton,
    withSkeleton,
  }
}

// 页面加载状态管理
export function usePageLoading() {
  const pageLoading = ref(false)
  const pageError = ref<Error | null>(null)
  const retryCount = ref(0)
  const maxRetries = ref(3)

  const setPageLoading = (state: boolean) => {
    pageLoading.value = state
    if (state) {
      pageError.value = null
    }
  }

  const setPageError = (error: Error) => {
    pageError.value = error
    pageLoading.value = false
  }

  const retry = async (fn: () => Promise<void>) => {
    if (retryCount.value >= maxRetries.value) {
      throw new Error('超过最大重试次数')
    }
    
    retryCount.value++
    try {
      await fn()
      retryCount.value = 0 // 成功后重置重试次数
    } catch (error) {
      if (retryCount.value >= maxRetries.value) {
        setPageError(error instanceof Error ? error : new Error(String(error)))
      }
      throw error
    }
  }

  const loadPage = async (fn: () => Promise<void>) => {
    try {
      setPageLoading(true)
      await fn()
    } catch (error) {
      setPageError(error instanceof Error ? error : new Error(String(error)))
      throw error
    } finally {
      setPageLoading(false)
    }
  }

  return {
    pageLoading,
    pageError,
    retryCount,
    maxRetries,
    setPageLoading,
    setPageError,
    retry,
    loadPage,
  }
}

// 批量加载状态管理
export function useBatchLoading() {
  const batchLoading = reactive<Record<string, boolean>>({})
  const batchErrors = reactive<Record<string, Error | null>>({})

  const setBatchLoading = (key: string, state: boolean) => {
    batchLoading[key] = state
    if (state) {
      batchErrors[key] = null
    }
  }

  const setBatchError = (key: string, error: Error) => {
    batchErrors[key] = error
    batchLoading[key] = false
  }

  const withBatchLoading = async <T>(
    key: string,
    fn: () => Promise<T>
  ): Promise<T> => {
    try {
      setBatchLoading(key, true)
      const result = await fn()
      return result
    } catch (error) {
      setBatchError(key, error instanceof Error ? error : new Error(String(error)))
      throw error
    } finally {
      setBatchLoading(key, false)
    }
  }

  const isAnyLoading = () => {
    return Object.values(batchLoading).some(loading => loading)
  }

  const clearBatch = (key?: string) => {
    if (key) {
      delete batchLoading[key]
      delete batchErrors[key]
    } else {
      Object.keys(batchLoading).forEach(k => {
        delete batchLoading[k]
        delete batchErrors[k]
      })
    }
  }

  return {
    batchLoading,
    batchErrors,
    setBatchLoading,
    setBatchError,
    withBatchLoading,
    isAnyLoading,
    clearBatch,
  }
}